<script setup lang="ts">
import { reactive, ref } from 'vue';
import type { FormInst, UploadFileInfo } from 'naive-ui';
import { useMessage, NButton, NCard, NForm, NFormItem, NInput, NInputNumber, NUpload } from 'naive-ui';
import router from '../router';
import { getToken } from '../util/token';
import { handleNoToken, listAllError } from '../util/handler';
import statusCode from '../api/statusCode';
import { ProductAttribute, updateProductAttributes } from '../api/product';

const prop = defineProps<{
  attribute: ProductAttribute;
}>();

const emit = defineEmits<{
  (e: 'closeProductAttr', type: 'update'): void
}>();

const formRef = ref<FormInst | null>(null);
const message = useMessage();

const productId = +router.currentRoute.value.params.productId;

const formValue = reactive<{ [P in Exclude<keyof ProductAttribute, 'attributeId'>]: ProductAttribute[P] }>({
  imgPath: '',
  productId,
  color: prop.attribute.color,
  unitPrice: prop.attribute.unitPrice,
  stock: prop.attribute.stock,
});

const rules = {
};

const formValidate = () => {
  return formRef.value?.validate();
};

const fileListRef = reactive<UploadFileInfo[]>([]);
const onFileChange = ({ file }: { file: UploadFileInfo }) => {
  if (file.status === 'removed') {
    fileListRef.length = 0;
    return;
  }
  if (file.file) {
    if (file.file.size <= 1 * 1000 * 1000) {
      fileListRef.length = 0;
      fileListRef.push(file);
    } else {
      message.info('图片需要小于1MB');
    }
  } else {
    message.error('File对象居然为null！');
  }
};

const handleButtonClick = async () => {
  try {
    await formValidate();

    const token = getToken();
    if (!token) {
      handleNoToken(message);
      return;
    }

    try {
      let img;
      let resp;
      if (fileListRef.length > 0) {
        // let it crash
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        img = fileListRef[0].file!;
        resp = await updateProductAttributes({ attributeId: prop.attribute.attributeId, ...formValue, img, token });
      } else {
        resp = await updateProductAttributes({ attributeId: prop.attribute.attributeId, ...formValue, token });
      }

      if (resp.status === statusCode.SUCCESS) {
        message.success(`成功更新商品SKU}`, {
          duration: 1500,
          onAfterLeave: () => window.location.reload()
        });
      } else {
        throw new Error(`错误码 ${resp.status}`);
      }
    } catch (error) {
      message.error("" + error);
    }

  } catch (errors) {
    if (errors instanceof Array) {
      listAllError(errors, message);
    } else {
      throw errors;
    }
  }
};

const handleCloseBtnClick = () => emit('closeProductAttr', 'update');
</script>

<template>
  <n-card title="更新商品SKU">
    <n-form
      :model="formValue"
      :rules="rules"
      :show-require-mark="false"
      ref="formRef"
    >
      <n-form-item
        label="商品颜色"
        path="color"
      >
        <n-input
          type="text"
          v-model:value="formValue.color"
          placeholder="商品颜色"
          :maxlength="16"
        />
      </n-form-item>
      <n-form-item
        label="单价"
        path="unitPrice"
      >
        <n-input-number
          v-model:value="formValue.unitPrice"
          placeholder="商品名称"
          :max="100000000"
          :min="0"
        >
          <template #prefix>
            ￥
          </template>
        </n-input-number>
      </n-form-item>
      <n-form-item
        label="库存"
        path="stock"
      >
        <n-input-number
          v-model:value="formValue.stock"
          placeholder="库存"
          :max="10000"
          :min="0"
        >
          <template #suffix>
            件
          </template>
        </n-input-number>
      </n-form-item>
      <n-form-item label="商品SKU图片">
        <n-upload
          v-model:file-list="fileListRef"
          accept="image/*"
          list-type="image"
          @change="onFileChange"
        >
          <n-button>选择图片</n-button>
        </n-upload>
      </n-form-item>
      <n-form-item>
        <n-button
          @click="handleButtonClick"
          type="primary"
          attr-type="submit"
        >
          创建
        </n-button>
        <n-button
          @click="handleCloseBtnClick"
          type="default"
          attr-type="button"
        >
          取消
        </n-button>
      </n-form-item>
    </n-form>
  </n-card>
</template>

<style scoped>
</style>
